package com.JUC.cha03.sec04;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.*;

public class CompletableFutureUseDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 添加线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            CompletableFuture.supplyAsync(() -> {

                System.out.println(Thread.currentThread().getName() + "---- come in supplyAsync");

                int result = ThreadLocalRandom.current().nextInt(10);

                if (result > 2){
                    int i = 10/0;
                }

                // 休眠1秒
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                System.out.println("---- 1秒后出结果：" + result);
                return result;

            }, threadPool).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("---- 计算完成，更新update：" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println("异常情况" + e.getCause() + "\t" + e.getMessage());
                return null;

            });

            System.out.println(Thread.currentThread().getName() + "执行其他任务");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }

    private static void future1() throws InterruptedException, ExecutionException {
        CompletableFuture<Object> supplyAsync = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + "---- come in supplyAsync");

            int result = ThreadLocalRandom.current().nextInt(10);

            // 休眠1秒
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("---- 1秒后出结果：" + result);
            return result;

        });

        System.out.println(Thread.currentThread().getName() + "执行其他任务");

        System.out.println(supplyAsync.get());
    }
}

